import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 定义用户角色类型
export type UserRole = 'admin' | 'student'

// 定义用户信息接口
export interface UserInfo {
  id: string
  username: string
  role: UserRole
  name: string
}

// 初始用户账号
const INITIAL_USERS = [
  {
    username: 'admin',
    password: 'admin123',
    role: 'admin',
    id: '1',
    name: '管理员'
  },
  {
    username: 'student',
    password: 'student123',
    role: 'student',
    id: '2',
    name: '学生'
  }
]

// 用户数据，初始化为初始用户列表
let USERS = [...INITIAL_USERS]

export const useUserStore = defineStore('CycleUser', () => {
  // 状态
  const userInfo = ref<UserInfo | null>(null)
  const token = ref<string>('')

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)

  // 方法
  // 登录方法
  const login = (username: string, password: string): boolean => {
    const user = USERS.find((u) => u.username === username && u.password === password)

    if (user) {
      userInfo.value = {
        id: user.id,
        username: user.username,
        role: user.role as UserRole,
        name: user.name,
      }
      token.value = `token-${user.id}-${Date.now()}`
      return true
    }
    return false
  }

  // 登出方法
  const logout = () => {
    userInfo.value = null
    token.value = ''
  }

  // 注册方法
  const register = (username: string, password: string, name: string): boolean => {
    // 检查用户名是否已存在
    const userExists = USERS.some((u) => u.username === username)
    if (userExists) {
      return false
    }

    // 生成新用户ID
    const newId = String(USERS.length + 1)

    // 创建新用户
    const newUser = {
      username,
      password,
      role: 'student' as UserRole, // 默认为学生角色
      id: newId,
      name,
    }

    // 添加到用户列表
    USERS.push(newUser)
    return true
  }

  return {
    userInfo,
    token,
    isLoggedIn,
    login,
    logout,
    register,
  }
}, {
  persist: true // 启用持久化存储
})
